var flag_treeSelect = false;
var GroupEmployeeModule = function() {
    var oTable = null;
    var editable = function() {
        return {
            init: function() {
                oTable = $('#modelEditable').dataTable({
                    "lengthMenu": [
                        [10, 15, 20, 50],
                        [10, 15, 20, 50]
                    ],
//                    "autoWidth": false,
                    "scrollX": true,
                    "displayLength": 10,
                    "language": {
                        "lengthMenu": "每页 _MENU_ 条记录",
                        "paginate": {
                            "previous": "上一页",
                            "next": "下一页"
                        },
                        "info": "从 _START_ 到  _END_ 条，总记录为 _TOTAL_ 条",
                        "infoEmpty": "记录数为0",
                    },
                    "sortable": false,
                    "columnDefs": [{
                        "data": null,
                        'sortable': false,
                        "defaultContent": "",
                        "targets": [6]
                    }],
                    "columns": [{
                        "data": "name",
                        "defaultContent": ""
                    }, {
                        "data": "employeeNo",
                        "defaultContent": ""
                    }, {
                        "data": "mobile",
                        "defaultContent": ""
                    }, {
                        "data": "account",
                        "defaultContent": ""
                    }, {
                        "data": "posPadId",
                        "defaultContent": ""
                    }, {
                        "data": "state",
                        "defaultContent": ""
                    }],
                    "filter": false,
                    "processing": false,
                    "serverSide": true,
                    "ajaxSource": ctx + "/groupEmployee/getGroupEmploee",
                    "serverMethod": "post",
                    "fnRowCallback": function(nRow, aData, displayIndex) {
                        nRow.children[0].id = aData.employeeId;
                        // var deptId = $("#groupId").val();
                        // if (deptId == aData.employeeId) {
                        //     $('td:eq(0)', nRow).html(aData.name + '(负责人)');
                        // } else {
                        //     $('td:eq(0)', nRow).html(aData.name);
                        // };
                        var posPad = $.trim(aData.posPadId);
                        if (posPad != undefined && posPad != '') {
                            $('td:eq(4)', nRow).html('已分配');
                        } else {
                            $('td:eq(4)', nRow).html('未分配');
                        }
                        var state = aData.state;
                        if (state == 1) {
                            $('td:eq(5)', nRow).html('在职');
                        } else if (state == 0) {
                            $('td:eq(5)', nRow).html('离职');
                        }

                        if (aData.admin == 1 && (aData.employeeNo == aData.orgCode) && (aData.orgId == aData.idcard)) {
                            var operation = '<a class="detail fa fa-bars fa-lg" title="详情" href="javascript:;"></a>';
                            $('td:eq(6)', nRow).html(operation);
                        } else {
                            var operation = '<a class="detail fa fa-bars fa-lg" title="详情" href="javascript:;"></a>' +
                                ' &nbsp;<a class="setLeader fa fa-child fa-lg" title="设为负责人" href="javascript:;"></a>' +
                                ' &nbsp;<a class="setRole fa fa-users fa-lg" title="分配角色" href="javascript:;"></a>' +
                                ' &nbsp;<a class="leave fa fa-user-times fa-lg" title="离职" href="javascript:;"></a>';
                            $('td:eq(6)', nRow).html(operation);
                        }
                        return nRow;
                    },
                    "fnServerData": function(ajaxSource, dataSet, fnCallback) {
                        var json = "";
                        var s;
                        for (var i = 0; i < dataSet.length; i++) {
                            s = dataSet[i];
                            if (s.name == 'sEcho') {
                                json = json + '"echo":' + s.value;
                            } else if (s.name == 'iDisplayStart') {
                                json = json + ',"start":' + s.value;
                            } else if (s.name == 'iDisplayLength') {
                                json = json + ',"pageSize":' + s.value;
                            }
                        }
                        var deptId = $("#groupId").val();
                        if (deptId == "") {
                            json = "{" + json + "}";
                        } else {
                            json = '{"deptId":"' + deptId + '",' + json + '}';
                        }
                        $.ajax({
                            "contentType": "application/json; charset=UTF-8",
                            "dataType": 'json',
                            "type": "POST",
                            "url": ajaxSource,
                            "data": json,
                            "success": fnCallback
                        });
                    },
                });
                // 设为负责人
                $('#modelEditable').on("click", "a.setLeader", (function(e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[0].id;
                    var chargemanId = $('#chargemanId').html();
                    var empName = nRow.children[0].innerText;
                    var groupName = $('#groupName').html();
                    if (id === chargemanId) {
                        bootbox.dialog({
                            message: empName + " 已经是 " + groupName + " 的负责人，不需要再设置！",
                            title: "温馨提示：",
                            buttons: {
                                main: {
                                    label: "确定",
                                    className: "btn btn-primary",
                                    callback: function() {

                                    }
                                }
                            }
                        });
                        return;
                    }
                    var remindStr = "";
                    if (chargemanId == "" || chargemanId == undefined) {
                        remindStr = "您确认要将 " + empName + " 设为 " + groupName + " 的负责人？";
                    } else {
                        remindStr = "您确认要将 " + empName + " 设为 " + groupName + " 的负责人？之前的负责人将变为普通员工。";
                    }
                    bootbox.confirm(remindStr, function(result) {
                        if (result) {
                            $.ajax({
                                type: "post",
                                url: ctx + "/employee/setLeader/" + id,
                                dataType: "json",
                                success: function(msg) {
                                    if (msg.code == 1) {
                                        bootbox.dialog({
                                            message: "已经设为负责人！",
                                            title: "温馨提示：",
                                            buttons: {
                                                main: {
                                                    label: "确定",
                                                    className: "btn btn-primary",
                                                    callback: function() {
                                                        window.location.reload();
                                                    }
                                                }
                                            }
                                        });
                                    } else {
                                        bootbox.alert(msg.message);
                                    }
                                },
                                error: function(msg) {
                                    bootbox.alert('设置负责人失败，请稍后重试！');
                                }
                            });
                        }
                    });

                }));
                // 离职
                $('#modelEditable').on("click", "a.leave", (function(e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[0].id;
                    bootbox.confirm("您确定要离职该员工?", function(result) {
                        if (result) {
                            $.ajax({
                                type: "post",
                                url: ctx + "/employee/leave/" + id,
                                dataType: "json",
                                success: function(msg) {
                                    if (msg.code == 1) {
                                        bootbox.dialog({
                                            message: "成功离职！",
                                            title: "温馨提示：",
                                            buttons: {
                                                main: {
                                                    label: "确定",
                                                    className: "btn btn-primary",
                                                    callback: function() {
                                                        window.location.reload();
                                                    }
                                                }
                                            }
                                        });
                                    } else {
                                        bootbox.alert(msg.message);
                                    }
                                },
                                error: function(msg) {
                                    bootbox.alert('离职失败，请稍后重试！');
                                }
                            });
                        }
                    });
                }));
                // 详情
                $('#modelEditable').on("click", "a.detail", (function(e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[0].id;
                    $.ajax({
                        type: "post",
                        url: ctx + "/employee/detail/" + id,
                        dataType: "json",
                        success: function(msg) {
                            $("#detailBody").empty(); // clean
                            var tmpl = $("#detailTemplate").tmpl(msg).appendTo("#detailBody");
                            if (msg.admin == 1) {
                                $("#detailGroupButton").hide()
                            }

                            var modalDetail = $('#detailModel').modal('show');
                            modalDetail.on("hidden.bs.modal", function(e) {
                                $(this).removeData();
                                $("#detailBody").empty();
                            });
                            //修改密码
                            $('#password').click(function(e) {
                                e.preventDefault();
                                $("#updatePasswdBody").empty();
                                var msg = {
                                    "employeeId": id
                                };
                                var tmpl = $("#updatePasswdTemplate").tmpl(msg).appendTo("#updatePasswdBody");
                                var modal = $('#updatePasswd').modal('show');
                                modal.on("hidden.bs.modal", function(e) {
                                    $(this).removeData();
                                    $("#updatePasswdBody").empty();
                                });

                                $('.i-checks').iCheck({
                                    radioClass: 'iradio_square-green'
                                });
                                
                                $('#loginPwd').on('ifChecked', function(event){ 
                                	$('#newpasswdDiv').css('display','none');
                                	$('#repasswdDiv').css('display','none');
                                });
                                
                                $('#loginPwd').on('ifUnchecked', function(event){ 
                                	$('#newpasswdDiv').css('display','block');
                                	$('#repasswdDiv').css('display','block');
                                });
                                
                                var validator = $('#updatePasswdForm').validate({
                                    rules: {
                                        state: {
                                            required: true
                                        },
                                        loginPwd: {
                                            required: true,
                                            rangelength: [6, 20]
                                        },
                                        workPwd: {
                                            required: true,
                                            rangelength: [6, 20],
                                            equalTo: "#newpasswd"
                                        }
                                    },
                                    messages: {
                                        state: {
                                            required: "密码类型"
                                        },
                                        loginPwd: {
                                            required: "新密码不能为空！",
                                            equalTo: "两次输入密码不一致！"
                                        },
                                        workPwd: {
                                            required: "重复新密码不能为空！",
                                            equalTo: "两次输入密码不一致！"
                                        }
                                    },
                                    success: function(label, element) {
                                        var icon = $(element).parent('.input-icon').children('i');
                                        $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
                                        icon.removeClass("fa-warning").addClass("fa-check");
                                    },

                                    submitHandler: function(form) {
                                        var json = $('form#updatePasswdForm').serializeJSON();
                                        $.ajax({
                                            type: "post",
                                            contentType: "application/json; charset=UTF-8",
                                            url: ctx + "/employee/updateEmpPassword",
                                            data: json,
                                            dataType: "json",
                                            success: function(msg) {
                                                if (msg.code == 1) {
                                                    modal.modal('hide');
                                                    bootbox.alert("重置员工密码成功！");
                                                } else {
                                                	modal.modal('hide');
                                                    bootbox.alert(msg.message);
                                                }
                                            },
                                            error: function(msg) {
                                                bootbox.alert(msg.message);
                                            }
                                        });
                                    }
                                });
                            });
                            //编辑
                            $('#edit').click((function(e) {
                                e.preventDefault();
                                $("#editEmpModelBody").empty();
                                if (msg.birthday != undefined) {
                                    msg.birthday = msg.birthday.substring(0, 10);
                                };
                                if (msg.entryTime != undefined) {
                                    msg.entryTime = msg.entryTime.substring(0, 10);
                                };
                                $("#editEmpModelBody").empty();
                                var tmpl = $("#editEmpModelTemplate").tmpl(msg).appendTo("#editEmpModelBody");
                                $('#detailModel').modal('hide');
                                var modal = $('#editEmpModel').modal('show');
                                modal.on("hidden.bs.modal", function(e) {
                                    $(this).removeData();
                                    $("#editEmpModelBody").empty();
                                });

                                var handleValidation = function() {
                                    var formAdd = $('#editEmpModelForm');
                                    $('#editEmpBtn').click(function() {
                                        timeout(this, 1);
                                        formAdd.submit();
                                    });
                                    jQuery.validator.addMethod("idcardLength", function(value, element) {
                                        var len = $.trim(value);
                                        if (len == '') {
                                            return true;
                                        }
                                        if (len.length != 15 && len.length != 18) {
                                            return false;
                                        }
                                        return true;
                                    }, "身份证只能是15位或18位长度！");
                                    jQuery.validator.addMethod("idcardRegex", function(value, element) {
                                        var len = $.trim(value);
                                        if (len == '') {
                                            return true;
                                        }
                                        var reg = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3})|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx]))$/;
                                        if (!reg.test(len)) {
                                            return false;
                                        }
                                        return true;
                                    }, "身份证格式不正确！");
                                    var validator = formAdd.validate({
                                        rules: {
                                            employeeName: {
                                                required: true,
                                                rangelength: [2, 20]
                                            },
                                            gender: {
                                                required: true,
                                                number: true
                                            },
                                            account: {
                                                required: true,
                                                remote: {
                                                    url: ctx + "/employee/check",
                                                    type: "post",
                                                    dataType: "json",
                                                    data: {
                                                        type: 1,
                                                        employeeId: id
                                                    }
                                                }
                                            },
                                            employeeNo: {
                                                required: true,
                                                rangelength: [3, 20],
                                                remote: {
                                                    url: ctx + "/employee/check",
                                                    type: "post",
                                                    dataType: "json",
                                                    data: {
                                                        type: 2,
                                                        employeeId: id
                                                    }
                                                }
                                            },
                                            mobile: {
                                                required: true,
                                                number: true,
                                                rangelength: [11, 30],
                                                remote: {
                                                    url: ctx + "/employee/check",
                                                    type: "post",
                                                    dataType: "json",
                                                    data: {
                                                        type: 3,
                                                        employeeId: id
                                                    }
                                                }
                                            },
                                            email: {
                                                //required: true,
                                                email: true,
                                                rangelength: [4, 120]
                                            },
                                            department: {
                                                //required: true,
                                                rangelength: [1, 30]
                                            },
                                            position: {
                                                //required: true,
                                                rangelength: [1, 30]
                                            },
                                            loginPwd: {
                                                required: true,
                                                rangelength: [6, 20]
                                            },
                                            workPwd: {
                                                required: true,
                                                rangelength: [6, 20]
                                            },
                                            entryTime: {
                                                //required: true,
                                                date: true
                                            },
                                            birthday: {
                                                //required: true,
                                                date: true
                                            },
                                            address: {
                                                //required: true,
                                                rangelength: [4, 120]
                                            },
                                            idcard: {
                                                idcardLength: true,
                                                idcardRegex: true,
                                                remote: {
                                                    url: ctx + "/employee/check",
                                                    type: "post",
                                                    dataType: "json",
                                                    data: {
                                                        type: 4,
                                                        employeeId: id
                                                    }
                                                }
                                            }
                                        },
                                        messages: {
                                            account: {
                                                remote: "该账号已经存在！"
                                            },
                                            loginPwd: {
                                                required: "登录密码不能为空！"
                                            },
                                            workPwd: {
                                                required: "工作密码不能为空！"
                                            },
                                            employeeNo: {
                                                remote: "该工号已经存在！"
                                            },
                                            mobile: {
                                                rangelength: "手机号码格式不正确！",
                                                remote: "该手机号码已经存在！"
                                            },
                                            idcard: {
                                                remote: "该身份证格式不正确，或已经存在！"
                                            }
                                        },
                                        success: function(label, element) {
                                            var icon = $(element).parent('.input-icon').children('i');
                                            // set success class to the control group
                                            $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
                                            icon.removeClass("fa-warning").addClass("fa-check");
                                        },

                                        submitHandler: function(form) {
                                            var json = $('form#editEmpModelForm').serializeObject();
                                            json.employeeId = id;
                                            $.ajaxFileUpload({
                                                url: ctx + '/employee/update',
                                                type: 'post',
                                                secureuri: false,
                                                fileElementId: 'file',
                                                dataType: 'json',
                                                data: json,
                                                success: function(data, status) {
                                                    if (data.code == 1) {
                                                        bootbox.dialog({
                                                            message: "更新信息成功",
                                                            title: "温馨提示：",
                                                            buttons: {
                                                                main: {
                                                                    label: "确定",
                                                                    className: "btn btn-primary",
                                                                    callback: function() {
                                                                        window.location.reload();
                                                                    }
                                                                }
                                                            }
                                                        });
                                                    } else {
                                                        bootbox.dialog({
                                                            message: data.message,
                                                            title: "温馨提示：",
                                                            buttons: {
                                                                main: {
                                                                    label: "确定",
                                                                    className: "btn btn-primary",
                                                                    callback: function() {
                                                                        window.location.reload();
                                                                    }
                                                                }
                                                            }
                                                        });
                                                    }
                                                },
                                                error: function(msg, status, e) {
                                                    bootbox.dialog({
                                                        message: "修改员工信息出错。",
                                                        title: "温馨提示：",
                                                        buttons: {
                                                            main: {
                                                                label: "确定",
                                                                className: "btn btn-primary",
                                                                callback: function() {
                                                                    window.location.reload();
                                                                }
                                                            }
                                                        }
                                                    });
                                                }
                                            });
                                        }
                                    });
                                }
                                handleValidation();
                                var deptId = $("#groupId").val();
                                var deptTree = function() {
                                    $('#deptTree').jstree({
                                        'plugins': {
                                            "wholerow": {},
                                            "checkbox": {
                                                "three-state": false
                                            },
                                            "types": {},
                                            "radio": {}
                                        },
                                        'core': {
                                            "themes": {
                                                "responsive": false
                                            },
                                            'data': {
                                                "url": ctx + "/groupEmployee/treeEmp/" + deptId,
                                                "data": function(node) {

                                                }
                                            }
                                        }
                                    }).on("changed.jstree", function(e, data) {
                                        if (data.node != undefined) {
                                            $('#deptId').val(data.node.id);
                                            $('#department').val(data.node.text);
                                        };
                                    });
                                };
                                deptTree();
                            }));
                            //分配设备
                            $('#device').click(function(e) {
                                e.preventDefault();
                                var modal = $('#bindDevice').modal('show');
                                modal.on("hidden.bs.modal", function(e) {
                                    $(this).removeData();
                                });
                                // clean
                                $('#posId').val('');
                                $('#padId').val('');
                                $('#posPadId').val('');

                                //Autocomplete
                                $("#padId").autocomplete({
                                    source: function(query, process) {
                                        $.post(ctx + "/device/queryPosPadAuto/" + query.term, {
                                            "matchCount": 200
                                        }, function(data) {
                                            var ebean = []
                                            for (var int = 0; int < data.length; int++) {
                                                var temp = [];
                                                temp.iSerialNumber = data[int].iSerialNumber;
                                                temp.pSerialNumber = data[int].pSerialNumber;
                                                temp.name = data[int].iSerialNumber;
                                                temp.value = data[int].iSerialNumber;
                                                temp.id = data[int].id;
                                                ebean.push(temp);
                                            }
                                            return process(ebean);
                                        });
                                    },
                                    search: function(event, ui) {
                                        // $("#posId").val('');
                                        // $("#padId").val('');
                                        // $("#posPadId").val('');
                                    },
                                    select: function(event, ui) {
                                        $("#padId").val(ui.item.iSerialNumber);
                                        $("#posId").val(ui.item.pSerialNumber);
                                        $("#posPadId").val(ui.item.id);
                                        var uistr = ui.item;
                                        // 阻止事件的默认行为
                                        event.preventDefault();
                                    }
                                });
                                // 分配
                                $('#saveBindDevice').unbind("click").click(function() {
                                    timeout(this, 2);
                                    var padId = $.trim($('#padId').val());
                                    var posId = $.trim($('#posId').val());
                                    var posPadId = $.trim($('#posPadId').val());
                                    if (padId == '' || posId == '' || posPadId == '') {
                                        bootbox.alert('设备信息不能为空！');
                                        return;
                                    }
                                    // 执行分配
                                    $.ajax({
                                        type: "post",
                                        contentType: "application/json; charset=UTF-8",
                                        url: ctx + "/device/doDistributionOther",
                                        data: JSON.stringify({
                                            "id": posPadId,
                                            "employeeId": id
                                        }),
                                        dataType: "json",
                                        success: function(msg) {
                                            if (msg.code == 1) {
                                                modal.modal('hide');
                                                bootbox.alert("员工设备分配成功！");
                                            } else {
                                                bootbox.alert(msg.message);
                                            }
                                        },
                                        error: function(msg) {
                                            bootbox.alert('Oh no,服务器出问题了！');
                                        }
                                    });
                                });
                            });
                        },
                        error: function(msg) {
                            bootbox.alert('获取员工详情错误！');
                        }
                    });
                }));
                // 设置角色
                $('#modelEditable').on("click", "a.setRole", (function(e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[0].id;
                    $.ajax({
                        type: "post",
                        url: ctx + "/userAuth/edit",
                        data: "employeeId=" + id,
                        dataType: "json",
                        success: function(msg) {
                            $("#setRoleBody").empty(); // clean
                            var tmpl = $("#setRoleTemplate").tmpl(msg).appendTo("#setRoleBody");
                            var modal = $('#setRoleModel').modal('show');
                            modal.on("hidden.bs.modal", function(e) {
                                $(this).removeData();
                                $("#setRoleBody").empty();
                            });

                            $('#roleTree').jstree({
                                'plugins': ["wholerow","checkbox", "types"],
                                'core': {
                                    "themes": {
                                        "responsive": false
                                    },
                                    'data': function(node, callback) { // 使用回调的方式
                                        var employeeId = $('#employeeId').val();
                                        if (employeeId == undefined || employeeId == "") {
                                            employeeId = "null";
                                        }
                                        if (node.id == "#") {
                                            callback({
                                                "id": "-1",
                                                "text": "系统角色",
                                                "state": {
                                                    "loaded": false
                                                },
                                                "icon": "fa fa-briefcase icon-warning"
                                            });
                                        } else {
                                            $.get(ctx + "/roles/tree?id=" + employeeId).done(function(d) {
                                                callback.call({
                                                    "id": "-1",
                                                    "text": "系统角色"
                                                }, d.children);
                                            });
                                        }
                                    }
                                },
                                "types": {
                                    "default": {
                                        "icon": "fa fa-folder icon-warning icon-lg"
                                    },
                                    "file": {
                                        "icon": "fa fa-file icon-warning icon-lg"
                                    }
                                }
                            }).on("changed.jstree", function(e, data) {
                                $('#roleIds').val(data.selected);
                                if (data.action == 'select_node' || data.action == 'deselect_node') {
                                    var json = data.instance.get_json();
                                    var array = json[0].children;
                                    var selected = '';
                                    for (var i = 0; i < array.length; i++) {
                                        var leaf = array[i];
                                        if (leaf.state.selected) {
                                            selected = selected + leaf.text + ',';
                                        }
                                    }
                                    $('#roleNames').val(selected.substring(0, selected.length - 1));
                                }
                            }).on("open_node.jstree", function(e, data) {
                                var id = data.node.id;
                                if (id == '-1') {
                                    var rootLoad = $('#rootLoad').val();
                                    if (rootLoad == "0") {
                                        $('#rootLoad').val("1");
                                        // 加载它的子节点，调用core.data加载
                                        data.instance.load_node(data.node);
                                    }
                                }
                                var ids = '';
                            	var nodes=$('#roleTree').jstree().get_checked(true); //使用get_checked方法 
	                            	$.each(nodes, function(i, n) {
	                            		var ids_temp = $(n).attr("id");
	                            		ids +=ids_temp +",";
                            	}); 
	                            //原本已经拥有的角色
	                            $('#old_roleIds').val(ids.substring(0,ids.length-1));
                            }).bind("select_node.jstree", function (e, data) {
                            }).bind("deselect_node.jstree", function (e, data) {
                            });
                            
                            $("#setRoleModelBtn").unbind("click").click(function() {
                                var json = $('form#setRoleModelForm').serializeJSON();
                                //当前选择的角色
                                var roleIds = $('#roleIds').val();
                                var toleArray = roleIds.split(",");
                                //原本已经拥有的角色
                                var old_roleIds = $('#old_roleIds').val();
                                var old_toleArray = old_roleIds.split(",");
                                var indexes = [];
                                var num = 0;
                                for (var i = 0; i < toleArray.length; i++) {
                                	var index_temp = old_roleIds.indexOf(toleArray[i]);
                                    if( index_temp == -1 && toleArray[i] != "-1") {
                                        indexes[num] = toleArray[i];
                                        num++;
                                    }
                                }
                                	modal.modal('hide');
                                    var myjson = "{\"roleIds\":\""+indexes.toString()+"\",\"employeeId\":\""+id+"\"}";
                                    //提交角色修改请求和发送验证码
                                    $.ajax({
                                        type: "post",
                                        contentType: "application/json; charset=UTF-8",
                                        url: ctx + "/userAuth/sendverification/",
                                        data:myjson,
                                        dataType: "json",
                                        success: function(msg) {
                                        	if(msg.code == 1){
                                        		if(msg.data.length > 0){
                                        			$("#input_verification").click();
                                        			$("#inputVerificationSpan").html("");
                                        			var str = "";
                                        			for(var i = 0; i < msg.data.length; i++){
                                        				str = str+"<label>角色名:"+msg.data[i].roleName+"</label>"+ 
            				    	                    		"<input  type=\"text\"  name=\""+msg.data[i].comMobile+"\" placeholder=\"请输入验证码\" class=\"form-control\"/>";
                                        			}
                                        			$("form#inputVerificationSpan").html(str);
                                        			//修改角色输入验证码确认按钮事件
                                                    $("#btn_modify_roles_verification").unbind("click").click(function(){
                                                    	var inputs = $("form#inputVerificationSpan").children("input");
                                                    	var json_temp = "{";
                                                    	for(var j = 0; j < inputs.length; j++){
                                                    		if(j==0){
                                                    			json_temp = json_temp +"\""+inputs[j].name+"\":\""+inputs[j].value+"\"";
                                                    		}else{
                                                    			json_temp = json_temp +",\""+inputs[j].name+"\":\""+inputs[j].value+"\"";
                                                    		}
                                                    	}
                                                    	json_temp = json_temp +"}";
                                                    	$.ajax({
                                                            type: "post",
                                                            contentType: "application/json; charset=UTF-8",
                                                            url: ctx + "/userAuth/verifyCode/"+json_temp,
                                                            dataType: "json",
                                                            success: function(msg) {
                                                            	if(msg.code == 1){
                                                            		modifyRoles();
                                                            		$("#dsimiss_input_verification").click();
                                                            	}else{
                                                            		bootbox.alert(msg.message);
                                                            	}
                                                            },
                                                            error: function(msg) {
                                                                bootbox.alert(msg.message);
                                                            }
                                                        });
                                        			});
                                        		}else{
                                        			modifyRoles();
                                        		}
                                        	}else if(msg.code == 2){
                                        		//修改角色信息不需要发送验证短信
                                        		modifyRoles();
                                        	}else{
                                        		bootbox.alert("发送验证码失败,请稍后再试！")
                                        	}
                                           /* var roleNames = $('#roleNames').val();
                                            //oTable.fnUpdate(roleNames, nRow, 2, false);
                                            modal.modal('hide');
                                            bootbox.alert("设置用户角色信息成功！");*/
                                        },
                                        error: function(msg) {
                                            bootbox.alert("修改角色失败!");
                                        }
                                    });
                                    //修改角色信息请求方法
                                    function modifyRoles(){
                                    	$.ajax({
	                                        type: "post",
	                                        contentType: "application/json; charset=UTF-8",
	                                        url: ctx + "/userAuth/update",
	                                        data: json,
	                                        dataType: "json",
	                                        success: function(msg) {
	                                            var roleNames = $('#roleNames').val();
	                                            //oTable.fnUpdate(roleNames, nRow, 2, false);
	                                            modal.modal('hide');
	                                            bootbox.alert("设置用户角色信息成功！");
	                                        },
	                                        error: function(msg) {
	                                            bootbox.alert(msg.message);
	                                        }
	                                    });
                                    }
                                });
                        },
                        error: function(msg) {
                            bootbox.alert(msg.message);
                        }
                    });
                }));
            }
        };
    }();
    var handleResourceTree = function() {
        var empTree;
        $('#resourceTree').jstree({
            'plugins': ["wholerow", "types"],
            'core': {
                "themes": {
                    "responsive": false
                },
                'data': {
                    "url": ctx + "/groupEmployee/tree"
                }
            },
            "types": {
                "default": {
                    "icon": "fa fa-folder icon-warning icon-lg"
                },
                "file": {
                    "icon": "fa fa-file icon-warning icon-lg"
                }
            }
        }).on("changed.jstree", function(e, data) {
            var groupId = data.selected;
            $('#groupId').val(groupId);
            $('#groupName')[0].innerHTML = data.instance._model.data[groupId].text;
            var empName = data.instance._model.data[groupId].original.employeeName;
            var empId = data.instance._model.data[groupId].original.employeeId;
            if (empName != undefined && empName != "") {
                $('#chargeman')[0].innerHTML = "负责人：" + empName;
            } else {
                $('#chargeman')[0].innerHTML = "";
            }
            if (empId != undefined && empId != "") {
                $('#chargemanId')[0].innerHTML = empId;
            } else {
                $('#chargemanId')[0].innerHTML = "";
            }
            oTable.fnClearTable();
            e.preventDefault();
        });
    };
    return {
        init: function() {
            editable.init();
            handleResourceTree();
        }
    };
}();

function checkRoles(id){
	flag_treeSelect = true;
	var flag = $('#roleTree').jstree('is_selected', "#"+id);
	if(flag){
		$('#roleTree').jstree('deselect_node', "#"+id);
	}else{
		$('#roleTree').jstree('select_node', "#"+id);
	}
	//var modal = $('#lookRolesModel').modal('show');

	$.ajax({
    	type:"post",
        url: ctx + "/roles/edit",
        data:"roleId=" + id,
        dataType:"json",
        success: function(msg){
        	$("#updateBody").empty();// clean
        	var tmpl = $("#updateTemplate").tmpl(msg).appendTo("#updateBody");
        	var s = false;
        	// 将权限树添加到更新模板上
        	$('#authTree').jstree({
                'plugins': ["wholerow", "checkbox", "types"],
                'core': {
                    "themes" : {
                        "responsive": false
                    },    
                    'data': function(node, callback) { // 使用回调的方式
                    	var roleId = $('#roleId').val();
                    	if (roleId == undefined || roleId == "") {
                    		roleId = "null";
                    	}
                    	if (node.id == "#") {
                    		callback({"id":"-1","text":"系统权限", "state":{"loaded":false}, "icon":"fa fa-briefcase icon-warning"});
                    	} else {
                    		$.get(ctx + "/authorities/tree?roleId=" + roleId).done(function (d) {
                    			callback.call({"id":"-1","text":"系统权限"}, d.children);
                    		});
                    	}
                    }
                },
                "types" : {
                    "default" : {
                        "icon" : "fa fa-folder icon-warning icon-lg"
                    },
                    "file" : {
                        "icon" : "fa fa-file icon-warning icon-lg"
                    },
                    "types": {
                        "disabled" : { 
                              "check_node" : true, 
                              "uncheck_node" : true 
                            } 
                    }
                }
            });
        	
        	var modal = $('#lookRolesModel').modal('show');
        	modal.on("hidden.bs.modal",function(e){
        		$(this).removeData();
        	});
        },
        error: function (msg) {
        	bootbox.alert(msg.message);
        }
    });

}